<template>
	<el-card class="table-list">
		<div slot="header">
			<slot name="header" :search="fetchList">
				<h3 class="el-card__title">{{title}}</h3>
				<tableSearch placeholder="请输入搜索关键字" @search="fetchList"></tableSearch>
			</slot>
		</div>
		<slot :data="localData" :loading="loading"></slot>
		<div style="text-align:right;">
			<el-pagination
				@size-change="handleSizeChange"
				@current-change="handleCurrentChange"
				:current-page="currentPage"
				:page-sizes="pageSizes"
				:page-size="pageSize"
				layout="total, sizes, prev, pager, next, jumper"
				:total="total"
			>
			</el-pagination>
		</div>
	</el-card>
</template>

<script>
  import request from '@/router/axios';
	export default {
		name: 'table-list',
		inheritAttrs: false,
		components: {
			tableSearch:()=> import('_c/tableSearch')
		},
		props: {
			title: {
				type: String,
				default: '标题'
			},
			action:{
				type: String,
				default: ''
			},
			method:{
				type: String,
				default: 'post'
			},
			map:{
				type: Object,
				default: () => ({})
			},
			data:{
				type:Array,
				default: () => []
			},
		},
		data() {
			return {
				loading:false,
				total:0,
				currentPage: 1,
				pageSizes: [5, 10, 15, 20],
				pageSize: 10,
				localData:[],
			};
		},
		created() {
			this.fetchList()
		},
		methods: {
			handleSizeChange(val) {
				this.pageSize = val
				this.fetchList()
			},
			handleCurrentChange(val) {
				this.currentPage = val
				this.fetchList()
			},
			fetchList(queryStr){
				const { data } = this
				//mock data
				if (data.length) {
					this.localData = data
					this.total = this.data.length
				// get data from serve
				}else{
					const {action,method,map,currentPage,pageSize} = this
					const query = {
						[map.current]:queryStr === '' ? 1 : currentPage,
						[map.size]:pageSize,
						[map.query]:queryStr || '',
					}
					const body = method.toLowerCase() === 'post' 
					? {data: query}
					: {params:query}
					
					this.loading = true
					request({
						url: action,
						method,
						...body
					}).then(res => {
						this.localData = res.data.records
						this.total = res.data.total
					})
					.catch(console.log)
					.finally(() => this.loading = false)
				}
			}
		},
	};
</script>
<style lang="scss" scoped>
	@import './style';
</style>
